import fs from "fs";
import path from "path";

type GetSpecifiedFileType = {
    /** 项目路径 */
    projectPath?: string;
    /** 路径前缀 */
    dirPath: string,
    /** 包含的文件夹 */
    includeDir?: string[]
    /** 排除的文件或文件夹 */
    excludeFileOrDir: string[],
    /** 文件后缀 */
    fileSuffix?: string[],
    // 遍历文件 递归程序参数
    fullPath?: string,
};
/** 获取指定文件夹下的文件 */
const getSpecifiedFile = (options: GetSpecifiedFileType) => {
    if (!options.fullPath) {
        options.fullPath = path.join(options.projectPath || '', options.dirPath || '')
    }
    let fileList: string[] = [];
    const dirs = fs.readdirSync(options.fullPath) || [];
    for (let dir of dirs) {
        const fullPath = path.join(options.fullPath, dir);

        if (
            options.includeDir &&
            !options.includeDir.some((item) => {
                const includePath = path.join(options.projectPath || '', options.dirPath || '', item);
                return (
                    fullPath.startsWith(includePath) || includePath.startsWith(fullPath)
                );
            })
        ) {
            continue;
        }
        if (options.excludeFileOrDir.some(item => {
            const excludePath = path.join(options.projectPath || '', options.dirPath || '', item)
            // console.log(excludePath, fullPath);
            return excludePath === fullPath
            // || fullPath.startsWith(excludePath) || excludePath.startsWith(fullPath)
        })
        ) {
            continue;
        }
        const stats = fs.statSync(fullPath);
        if (stats.isDirectory()) {
            fileList = fileList.concat(getSpecifiedFile({
                ...options,
                fullPath: fullPath,
            }));
        } else if (options?.fileSuffix?.includes(path.extname(fullPath)) || !options?.fileSuffix) {
            fileList.push(fullPath.replace(path.join(options.projectPath || '', options.dirPath || ''), ''));
        }
    }
    return fileList;
}

export default getSpecifiedFile